package com.wn.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wn.bean.DataRoles;
import com.wn.bean.Permission;
import com.wn.bean.R;
import com.wn.bean.RolePermission;
import com.wn.service.IPermissionService;
import com.wn.service.IRolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yellow Docter
 * @since 2022-05-16
 */
@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IRolePermissionService rolePermissionService;

    /**
     *     var zNodes =[
     *         { id:1, pId:0, name:"系统操作", open:true},
     *         { id:11, pId:1, name:"用户管理", open:true},
     *         { id:111, pId:11, name:"用户管理添加"},
     *         { id:112, pId:11, name:"用户管理删除"},
     *         { id:12, pId:1, name:"角色管理", open:true},
     *         { id:121, pId:12, name:"角色管理添加"},
     *         { id:122, pId:12, name:"角色管理删除"},
     *         { id:2, pId:0, name:"随意勾选 2", checked:true, open:true},
     *         { id:21, pId:2, name:"随意勾选 2-1"},
     *         { id:22, pId:2, name:"随意勾选 2-2", open:true},
     *         { id:221, pId:22, name:"随意勾选 2-2-1", checked:true},
     *         { id:222, pId:22, name:"随意勾选 2-2-2"},
     *         { id:23, pId:2, name:"随意勾选 2-3"}
     *     ];
     */

    @GetMapping
    public List<Map<String,Object>> getPermission(){


        List<Map<String,Object>> list = new ArrayList<>();
        // 01 所有的权限查询出来
        List<Permission> permissions = permissionService.list(null);
        //02 把 permissions 转成一个map
        for (Permission permission : permissions) {

            Map<String,Object> map = new HashMap();
            map.put("id",permission.getPid());
            map.put("pId",permission.getParentid());
            map.put("name",permission.getPname());

            list.add(map);
        }

        return list;

    }

    /**
     * 把所有的权限 查询出来
     *      1. 查询所有的  Permission
     *      2.需要把Permission 对象转成 前端的tree的数据格式
     *
     * @param rid
     * @return
     */
    @GetMapping("/{rid}")
    public List<Map<String,Object>> getPermissionByRid(@PathVariable Integer rid){
       List<Map<String,Object>> list =  permissionService.findPermission(rid);
        return list;
    }

    @PutMapping
    public R updatePermission(@RequestBody DataRoles dataRoles){
        System.out.println("dataRoles = " + dataRoles);

        rolePermissionService.updatePermission(dataRoles);

        return R.OK();
    }

}
